package delay;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class OrderDelay implements Delayed {

    private Long timeout;

    private String orderId;

    OrderDelay(String orderId, Long timeout){
        this.orderId = orderId;
        this.timeout = timeout + System.nanoTime();
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(timeout - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed other) {
        if(other == this){
            return 0;
        }
        OrderDelay orderDelay = (OrderDelay) other;

        long diff = getDelay(TimeUnit.NANOSECONDS) - orderDelay.getDelay(TimeUnit.NANOSECONDS);

        return (diff == 0) ? 0 : (diff < 0 ? (-1): 1);
    }

    void print(){
        System.out.println(orderId + "编号的订单要删除了....");
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("00000001");
        list.add("00000002");
        list.add("00000003");
        list.add("00000004");
        list.add("00000005");

        DelayQueue<OrderDelay> queue = new DelayQueue<>();

        long start = System.currentTimeMillis();

        for(int i = 0; i < 5; i++){

            queue.put(new OrderDelay(list.get(i), TimeUnit.NANOSECONDS.convert(3, TimeUnit.SECONDS)));

            try {

                queue.take().print();

            } catch (InterruptedException e) {

                e.printStackTrace();
            }

            System.out.println("after " + (System.currentTimeMillis() - start) + " milliseconds");
        }
    }
}
